<template>
  <div class="code-example">
    <div class="code-header">
      <span class="code-title">{{ title }}</span>
      <a-button size="small" @click="copyCode" :icon="h(CopyOutlined)">
        {{ copied ? '已复制' : '复制代码' }}
      </a-button>
    </div>
    <div class="code-content">
      <pre><code>{{ code }}</code></pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, h } from 'vue'
import { CopyOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

interface Props {
  title?: string
  code: string
  language?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: '代码示例',
  language: 'javascript'
})

const copied = ref(false)

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code)
    copied.value = true
    message.success('代码已复制到剪贴板')
    setTimeout(() => {
      copied.value = false
    }, 2000)
  } catch (err) {
    console.log(err)

    message.error('复制失败，请手动复制')
  }
}
</script>

<style scoped>
.code-example {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  overflow: hidden;
  margin: 16px 0;
  background: #f8fafc;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #ffffff;
  border-bottom: 1px solid #e2e8f0;
}

.code-title {
  font-size: 14px;
  font-weight: 600;
  color: #4a5568;
}

.code-content {
  background: #1a202c;
  color: #e2e8f0;
  padding: 16px;
  overflow-x: auto;
}

.code-content pre {
  margin: 0;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.code-content code {
  color: #e2e8f0;
  font-family: inherit;
}
</style>
